package hhm.android.my

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.ActivityEvent
import hhm.android.library.bus.Bus
import hhm.android.library.utils.GridSpacingItemDecoration
import hhm.android.library.utils.OnMultiClickListener
import siau.android.base.*
import siau.android.http.model.*
import siau.android.library.KeyString

@Route(path = FRIEND_LIST_ROUTE)
class FriendListActivity : SBBaseActivity() {

    private var isCreator = SBApplication.userData.isCreator == 1
    lateinit var recycler: RecyclerView
    lateinit var btn: TextView
    lateinit var adapter: FriendListAdapter
    val list = ArrayList<FriendModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        setContentView(R.layout.activity_friend_list)
        initTitleWithLine(getString(R.string.friend_list))

        recycler = findViewById(R.id.activity_friend_list_recycler)
        btn = findViewById(R.id.activity_friend_list_btn)

        recycler.layoutManager = GridLayoutManager(this, 3)
        recycler.addItemDecoration(GridSpacingItemDecoration(3, dp2px(12f), true))
        adapter = FriendListAdapter(this, list, object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                val pos = v?.tag as Int
                adapter.list.forEach {
                    it.select = false
                }
                adapter.list[pos].select = true
                adapter.notifyDataSetChanged()
            }
        }, object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                getSureDialog(this@FriendListActivity, {
                    val b = v?.tag as FriendModel
                    showLoadingFragment(R.id.activity_friend_list_fl)
                    val r = DeleteFamilyMemberRequest(b.familyId, b.userFamilyId)
                    HttpHelper().deleteFamilyMember(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                        initData()
                    }, {
                        removeLoadingFragment()
                        showToast(it.message)
                    })
                }, null, "", getString(R.string.sure_delete_this_guy), showTitle = false)
            }
        }, object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                getSureDialog(this@FriendListActivity, {
                    val b = v?.tag as FriendModel
                    showLoadingFragment(R.id.activity_friend_list_fl)
                    val r = UserIdModel(b.userId)
                    HttpHelper().makeOverFamily(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                        SBApplication.userData.isCreator = 0

                        btn.text = getString(R.string.quit)
                        btn.setOnClickListener(object : OnMultiClickListener() {
                            override fun onMultiClick(v: View?) {
                                getSureDialog(this@FriendListActivity, {
//                                    if (SBApplication.startCalculate.value == true) {
//                                        SBApplication.startCalculate.value = false
//                                    }
                                    showLoadingFragment(R.id.activity_friend_list_fl)
                                    val r = FamilyIdModel(SBApplication.userData.familyId)
                                    HttpHelper().quitFamily(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                                        removeLoadingFragment()

                                        SBApplication.userData = it
                                        SBApplication.hasWeightMachine = false
                                        SBApplication.hasHeightMachine = false
                                        SBApplication.hasToothBrushMachine = false
                                        it.deviceList?.forEach { d ->
                                            if (d.deviceType == 1) {
                                                SBApplication.hasWeightMachine = true
                                            } else if (d.deviceType == 2) {
                                                SBApplication.hasHeightMachine = true
                                            }else if (d.deviceType == 3) {
                                                SBApplication.hasToothBrushMachine = true
                                            }
                                        }

                                        Bus.getDefault().post(KeyString.quitFamily)

                                        finish()
                                    }, {
                                        removeLoadingFragment()
                                        showToast(it.message)
                                    })
                                }, content = getString(R.string.sure_quit_friend_list), showTitle = false)
                            }
                        })

                        isCreator = false
                        b.select = false
                        adapter.notifyDataSetChanged()
                        removeLoadingFragment()
                    }, {
                        removeLoadingFragment()
                        showToast(it.message)
                    })
                }, null, "", getString(R.string.sure_give_other_identity), showTitle = false)
            }
        })
        recycler.adapter = adapter

        if (isCreator) {
            btn.text = getString(R.string.invite)
            btn.setOnClickListener(object : OnMultiClickListener() {
                override fun onMultiClick(v: View?) {
                    startActivity(Intent(this@FriendListActivity, InviteFriendActivity::class.java))
                }
            })
        } else {
            btn.text = getString(R.string.quit)
            btn.setOnClickListener(object : OnMultiClickListener() {
                override fun onMultiClick(v: View?) {
                    HttpHelper().familyCount()?.subscribe({
                        if (it.familyCount > 1) {
                            getSureDialog(this@FriendListActivity, {
//                                if (SBApplication.startCalculate.value == true) {
//                                    SBApplication.startCalculate.value = false
//                                }
                                showLoadingFragment(R.id.activity_friend_list_fl)
                                val r = FamilyIdModel(SBApplication.userData.familyId)
                                HttpHelper().quitFamily(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                                    removeLoadingFragment()

                                    SBApplication.userData = it
                                    SBApplication.hasWeightMachine = false
                                    SBApplication.hasHeightMachine = false
                                    SBApplication.hasToothBrushMachine = false
                                    it.deviceList?.forEach { d ->
                                        if (d.deviceType == 1) {
                                            SBApplication.hasWeightMachine = true
                                        } else if (d.deviceType == 2) {
                                            SBApplication.hasHeightMachine = true
                                        } else if (d.deviceType == 3) {
                                            SBApplication.hasToothBrushMachine = true
                                        }
                                    }

                                    Bus.getDefault().post(KeyString.quitFamily)

                                    finish()
                                }, {
                                    removeLoadingFragment()
                                    showToast(it.message)
                                })
                            }, content = getString(R.string.sure_quit_friend_list), showTitle = false)
                        } else {
                            getSureDialog(this@FriendListActivity, {
//                                if (SBApplication.startCalculate.value == true) {
//                                    SBApplication.startCalculate.value = false
//                                }
                                showLoadingFragment(R.id.activity_friend_list_fl)
                                val r = FamilyIdModel(SBApplication.userData.familyId)
                                HttpHelper().quitFamily(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                                    removeLoadingFragment()
                                    SBApplication.clearBlueToothData()

                                    SBApplication.communityChildId = -1
                                    SBApplication.userData.userStatus = 2
                                    SBApplication.hasWeightMachine = false
                                    SBApplication.hasHeightMachine = false
                                    SBApplication.hasToothBrushMachine = false
                                    SBApplication.refreshMainActivityUI = false
                                    SBApplication.becomeCreator = false

                                    ARouter.getInstance().build(SELECT_IDENTITY).withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK).navigation()

                                }, { i ->
                                    removeLoadingFragment()
                                    showToast(i.message)
                                })
                            }, content = getString(R.string.u_only_have_one_family_sure_quit), showTitle = false)
                        }
                    }, {
                        showToast(it.message)
                    })
                }
            })
        }

        showLoadingFragment(R.id.activity_friend_list_fl)
        initData()
    }

    private fun initData() {
        HttpHelper().friendList()?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
            removeLoadingFragment()
            adapter.setData(it)
        }, {
            removeLoadingFragment()
            showToast(it.message)
        })
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val type = intent?.getStringExtra(KeyString.type)
        if (KeyString.becomeCreator == type) {
            isCreator = SBApplication.userData.isCreator == 1
            btn.text = getString(R.string.invite)
            btn.setOnClickListener(object : OnMultiClickListener() {
                override fun onMultiClick(v: View?) {
                    startActivity(Intent(this@FriendListActivity, InviteFriendActivity::class.java))
                }
            })
        }
    }
}